// 对axios进行二次封装
import axios from 'axios'
import store from '@/store'

const instance = axios.create({
  // baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net'
  baseURL: 'https://apipc-xiaotuxian-front.itheima.net'
  // timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use(config => {
// Do something before request is sent
  const token = store.state.user.profile.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => {
// Do something with request error
  return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(response => {
// Do something before response is sent
  return response.data
}, error => {
// Do something with response error
  return Promise.reject(error)
})

// 二次封装
function request (url, method, data) {
  // console.log(url)
  return instance({
    method,
    url,
    // 属性名加[] 表示动态属性名 可以写表达式
    [method.toLowerCase() === 'get' ? 'params' : 'data']: data
  })
}
export default request
